package com.ms.seguridad.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.util.TextEscapeUtils;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.StringTokenizer;

/**
 * Derived from Spring Security 3.0.7
 * User: AW
 * Date: 24/02/13
 */
public class DpwcAuthenticationFilter extends org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter {
    //~ Static fields/initializers =====================================================================================
    protected final Logger LOG = LoggerFactory.getLogger(DpwcAuthenticationFilter.class);
    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "j_username";
    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "j_password";
    public static final String SPRING_SECURITY_FORM_PORTAL_KEY = "j_portal";
    public static final String SPRING_SECURITY_CRYPT = "j_token";
    public static final String SPRING_SECURITY_LAST_USERNAME_KEY = "SPRING_SECURITY_LAST_USERNAME";

    private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
    private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
    private String portalParameter = SPRING_SECURITY_FORM_PORTAL_KEY;
    private String cryptParameter = SPRING_SECURITY_CRYPT;
    private boolean postOnly = true;

    //~ Constructors ===================================================================================================

    public DpwcAuthenticationFilter() {
        super("/j_spring_security_check");
    }

//    @Override
//    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
//
//        super.doFilter(req, res, chain);    //To change body of overridden methods use File | Settings | File Templates.
//    }

    //~ Methods ========================================================================================================
    private String token(String param, String paramName) {
        StringTokenizer tokenizer = new StringTokenizer(param, "&");
        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            String patron = paramName + "=";
            int index = token.indexOf(patron);
            if (index != -1) {
                return token.substring(index + patron.length());
            }
        }
        return null;
    }

    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        String username = obtainUsername(request);
        String password = obtainPassword(request);
//        if (!isCrypt(request)) {
//            password = NcCrypt.encryptPassword(obtainPassword(request));
//            password = NcCrypt.encryptPassword(password);
//        }
        String portal = obtainPortal(request);

        if (username == null) username = "";
        if (password == null) password = "";
        if (portal == null) portal = "";
        username = username.trim();
        String remoteAddress = request.getRemoteAddr();
        DpwcAuthenticationToken authRequest = new DpwcAuthenticationToken(username, password, portal, remoteAddress);

        // Place the last username attempted into HttpSession for views
        HttpSession session = request.getSession(false);

        if (session != null || getAllowSessionCreation()) {
            request.getSession().setAttribute(SPRING_SECURITY_LAST_USERNAME_KEY, TextEscapeUtils.escapeEntities(username));
        }

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        Authentication authenticate = this.getAuthenticationManager().authenticate(authRequest);
        return authenticate;
    }

    protected String obtainPortal(HttpServletRequest request) {
        //return request.getParameter(portalParameter);
//        return getParameter(portalParameter, request);
        return "2";
    }

    /**
     * Enables subclasses to override the composition of the password, such as by including additional values
     * and a separator.<p>This might be used for example if a postcode/zipcode was required in addition to the
     * password. A delimiter such as a pipe (|) should be used to separate the password and extended value(s). The
     * <code>AuthenticationDao</code> will need to generate the expected password in a corresponding manner.</p>
     *
     * @param request so that request attributes can be retrieved
     * @return the password that will be presented in the <code>Authentication</code> request token to the
     * <code>AuthenticationManager</code>
     */
    protected String obtainPassword(HttpServletRequest request) {
        //return request.getParameter(passwordParameter);
        return getParameter(passwordParameter, request);
    }

    /**
     * Enables subclasses to override the composition of the username, such as by including additional values
     * and a separator.
     *
     * @param request so that request attributes can be retrieved
     * @return the username that will be presented in the <code>Authentication</code> request token to the
     * <code>AuthenticationManager</code>
     */
    protected String obtainUsername(HttpServletRequest request) {
        //return getParameter(usernameParameter,request);
        return getParameter(usernameParameter, request);
    }

    /**
     * Provided so that subclasses may configure what is put into the authentication request's details
     * property.
     *
     * @param request     that an authentication request is being created for
     * @param authRequest the authentication request object that should have its details set
     */
    protected void setDetails(HttpServletRequest request, DpwcAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    /**
     * Sets the parameter name which will be used to obtain the username from the login request.
     *
     * @param usernameParameter the parameter name. Defaults to "j_username".
     */
    public void setUsernameParameter(String usernameParameter) {
        Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
        this.usernameParameter = usernameParameter;
    }

    /**
     * Sets the parameter name which will be used to obtain the password from the login request..
     *
     * @param passwordParameter the parameter name. Defaults to "j_password".
     */
    public void setPasswordParameter(String passwordParameter) {
        Assert.hasText(passwordParameter, "Password parameter must not be empty or null");
        this.passwordParameter = passwordParameter;
    }

    /**
     * Defines whether only HTTP POST requests will be allowed by this filter.
     * If set to true, and an authentication request is received which is not a POST request, an exception will
     * be raised immediately and authentication will not be attempted. The <tt>unsuccessfulAuthentication()</tt> method
     * will be called as if handling a failed authentication.
     * <p/>
     * Defaults to <tt>true</tt> but may be overridden by subclasses.
     */
    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }

    public final String getUsernameParameter() {
        return usernameParameter;
    }

    public final String getPasswordParameter() {
        return passwordParameter;
    }

    private String getParameter(String paramName, HttpServletRequest request) {
//        if(isCrypt(request)){
//            String value=request.getParameter(paramName);
//            return NcCrypt.decryptPassword(value);
//        }else{
//         return request.getParameter(paramName);
//        }
        return request.getParameter(paramName);
    }

    private boolean isCrypt(HttpServletRequest request) {
        String crypt = request.getParameter(cryptParameter);
        return crypt != null && "1".equals(crypt);
    }
}
